﻿Imports <xmlns:log="urn:myLogConfig">
Imports System.IO
Imports System.Threading
Imports System.Windows.Threading

Public Class ViewLogsToMoveUC

    Friend r As MainWindow
    Friend stopBool As Boolean = True
    Const msg_launch = "Lancer le scan"
    Const msg_stop = "Arrêter le scan"
    Const msg_finished = "Le scan de l'ensemble des chemins est terminé"
    Const msg_cancelled = "Le scan de l'ensemble des chemins a été arrêté"

    Private Sub UserControl_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        r = MainWindow.moiMeme
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles BTN_launchScan.Click
        If BTN_launchScan.Content = msg_launch Then
            BTN_launchScan.Content = msg_stop
            launchScan()
        Else
            BTN_launchScan.Content = msg_launch
            stopScan()
        End If
    End Sub

    Sub populate()
        Dim lesPlateformes = (From plt In r.masterDoc...<log:plateforme> Select plt).ToList

        For Each unePlateformeXml As XElement In lesPlateformes

            Dim noeudPlateforme As New TreeViewItemWithIcons

            'Ajout des plateformes a la racine du treeview
            Dim unePlateforme As New Plateforme(unePlateformeXml)

            'Ajout des serveurs a la racine du plateformes
            Dim serveursXML = unePlateformeXml.<log:serveur>

            For Each unServeurXml As XElement In serveursXML
                Dim unServeur As New Serveur(unServeurXml, unePlateforme)

                Dim noeudServeur As New TreeViewItemWithIcons

                Dim cheminsXML = unServeurXml.<log:chemin>

                For Each cheminXml As XElement In cheminsXML
                    Dim unChemin As New Chemin(cheminXml, unServeur)
                    Dim noeudChemin As New TreeViewItemWithIcons

                    noeudChemin.HeaderText = unChemin.destDossier
                    noeudChemin.Tag = unChemin
                    noeudChemin.tagXML = cheminXml
                    noeudServeur.Items.Add(noeudChemin)
                Next

                noeudServeur.HeaderText = unServeur.nom
                noeudServeur.Tag = unServeur
                noeudServeur.tagXML = unServeurXml
                noeudPlateforme.Items.Add(noeudServeur)
            Next

            noeudPlateforme.Tag = unePlateforme
            noeudPlateforme.tagXML = unePlateformeXml
            noeudPlateforme.HeaderText = unePlateforme.nom
            TreeView_alltests.Items.Add(noeudPlateforme)
        Next
    End Sub

    Sub launchScan()
        stopBool = False
        TreeView_alltests.Items.Clear()
        populate()
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.loading, System.Drawing.Bitmap))
        loadingImg.StartAnimate()

        For Each noeudPlateforme As TreeViewItemWithIcons In TreeView_alltests.Items

            Dim unePlateforme = DirectCast(noeudPlateforme.Tag, Plateforme)
            noeudPlateforme.Icon = My.Resources.ic_accept.ToImageSource
            noeudPlateforme.IsExpanded = True
            For Each noeudServeur As TreeViewItemWithIcons In noeudPlateforme.Items
                noeudServeur.IsExpanded = True
                Dim unServeur = DirectCast(noeudServeur.Tag, Serveur)
                noeudServeur.Icon = My.Resources.micro_accept.ToImageSource

                For Each noeudChemin As TreeViewItemWithIcons In noeudServeur.Items
                    Dim unChemin = DirectCast(noeudChemin.Tag, Chemin)
                    noeudChemin.Icon = My.Resources.micro_accept.ToImageSource

                    Dim noeudCheminSource As New TreeViewItemWithIcons
                    noeudChemin.Items.Add(noeudCheminSource)
                    noeudCheminSource.HeaderText = "Source: " & unChemin.getFullPathSource

                    Dim noeudCheminDestination As New TreeViewItemWithIcons
                    noeudChemin.Items.Add(noeudCheminDestination)
                    noeudCheminDestination.HeaderText = "Destination: " & unChemin.getFullPathDestination

                    '------------ Logs Source
                    Dim rtnLog = getSourceLogs(unePlateforme, unChemin)
                    updateTreeViewNodes(rtnLog.except, noeudCheminSource, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathSource)

                    '------------ Test Destination
                    Dim excepTestDest = checkDestinationOk(unChemin.getFullPathDestination)
                    updateTreeViewNodes(excepTestDest, noeudCheminDestination, noeudChemin, noeudServeur, noeudPlateforme, unChemin.getFullPathDestination)

                    'Succès
                    If excepTestDest Is Nothing AndAlso rtnLog.except Is Nothing Then

                        If rtnLog.fichiers IsNot Nothing Then
                            Dim selectedFiles = pathManager.getFilesToMove(rtnLog.fichiers, unServeur.nbJourRetention)
                            showLogsFiles(selectedFiles, noeudChemin)
                        End If

                        If rtnLog.repertoires IsNot Nothing Then
                            Dim selectedFolders = pathManager.getFoldersToMove(rtnLog.repertoires, unServeur.nbJourRetention)
                            showLogsFolders(selectedFolders, noeudChemin)
                        End If
                    End If

                    If stopBool Then : Exit Sub : End If
                Next
            Next
        Next
        scanFinished()
    End Sub

    Sub scanFinished()
        loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_accept, System.Drawing.Bitmap))
        BTN_launchScan.Content = msg_launch
        stopBool = True
        r.consoleOut.addItim(New ConsoleTypes.msg(msg_finished, ""))
    End Sub

    Private Function getSourceLogs(plt As Plateforme, chm As Chemin) As SourceLogReturn

        Dim outResult As New SourceLogReturn
        Dim tstart As ParameterizedThreadStart = New ParameterizedThreadStart(Sub()
                                                                                  Try
                                                                                      Using New Impersonator(plt.login, plt.domain, plt.password)
                                                                                          If chm.typeLogs = cst.typeLogs.dossiers Then
                                                                                              outResult.repertoires = New DirectoryInfo(chm.getFullPathSource).GetDirectories
                                                                                          End If
                                                                                          If chm.typeLogs = cst.typeLogs.fichiers Then
                                                                                              outResult.fichiers = New DirectoryInfo(chm.getFullPathSource).GetFiles
                                                                                          End If
                                                                                      End Using
                                                                                  Catch ex As Exception
                                                                                      outResult.except = ex
                                                                                  End Try
                                                                              End Sub)

        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop

        Return outResult
    End Function


    Private Function checkDestinationOk(fullPath As String) As Exception

        Dim outException As Exception = Nothing
        Dim credArchivage = r.masterDoc...<log:credArchivage>

        Dim tstart As ThreadStart = New ThreadStart(Sub()
                                                        Try
                                                            Using New Impersonator(credArchivage.@login, credArchivage.@domain, credArchivage.@password)
                                                                pathManager.testFullAccessDirectory(fullPath)
                                                            End Using
                                                        Catch ex As Exception
                                                            outException = ex
                                                        End Try
                                                    End Sub)
        Dim theThread = New Thread(tstart)
        theThread.Start()

        Do Until Not theThread.IsAlive
            Thread.Sleep(10)
            r.DoEvents()
        Loop
        Return outException
    End Function

    Private Sub showLogsFiles(selectedFiles As List(Of FileInfo), ByRef leNoeudChemin As TreeViewItemWithIcons)

        Dim dates = (From dt In selectedFiles Select dt.getDateFromName Distinct).ToList

        For Each dt In dates
            Dim madt = dt
            Dim filesForDate = (From fic In selectedFiles Select fic Where fic.getDateFromName = madt).ToList
            Dim maxSizeName = (From fic In selectedFiles Select fic.Name.Length).Max

            For Each fichier In filesForDate
                Dim fichier_x = fichier

                Dim noeudFichier As New TreeViewItemWithIcons
                noeudFichier.HeaderText = fichier_x.Name & getConstantSpace(fichier_x.Name, maxSizeName, 5) & "(" & fichier_x.getDateFromName.toFrenchShort & ")"
                noeudFichier.Tag = fichier_x
                noeudFichier.Icon = My.Resources.logfile.ToImageSource
                noeudFichier.BringIntoView()
                leNoeudChemin.Items.Add(noeudFichier)
            Next

        Next

    End Sub


    Private Sub showLogsFolders(selectedFolders As List(Of DirectoryInfo), ByRef leNoeudChemin As TreeViewItemWithIcons)

        Dim dates = (From dt In selectedFolders Select dt.getDateFromName Distinct).ToList

        For Each dt In dates
            Dim madt = dt
            Dim foldersForDate = (From fic In selectedFolders Select fic Where fic.getDateFromName = madt).ToList
            Dim maxSizeName = (From fic In selectedFolders Select fic.Name.Length).Max

            For Each doss In foldersForDate
                Dim dossier = doss

                Dim noeudDossier As New TreeViewItemWithIcons
                noeudDossier.HeaderText = dossier.Name & getConstantSpace(dossier.Name, maxSizeName, 5) & "(" & dossier.getDateFromName.toFrenchShort & ")"
                noeudDossier.Tag = dossier
                noeudDossier.Icon = My.Resources.logFolder.ToImageSource
                noeudDossier.BringIntoView()
                leNoeudChemin.Items.Add(noeudDossier)
            Next

        Next

    End Sub

    Private Sub TreeView1Item_selected(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        miniConsole.Document.Blocks.Clear()
        Dim elem As TreeViewItemWithIcons = DirectCast(e.Source, TreeViewItemWithIcons)

        If elem.Tag IsNot Nothing Then

            Select Case elem.Tag.GetType.Name
                Case GetType(String).Name
                    Dim message = DirectCast(elem.Tag, String)
                    If message.StartsWith("Accès ok:") Then
                        miniConsole.Foreground = Brushes.Green
                    Else
                        miniConsole.Foreground = Brushes.Red
                    End If
                    miniConsole.addTextPair("", message)
                Case GetType(Plateforme).Name
                    Dim plt = DirectCast(elem.Tag, Plateforme)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Plateforme")
                    miniConsole.addTextPair("Nom: ", plt.nom)
                    miniConsole.addTextPair("Destination: ", plt.destination)
                Case GetType(Serveur).Name
                    Dim srv = DirectCast(elem.Tag, Serveur)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Serveur")
                    miniConsole.addTextPair("Nom: ", srv.nom)
                    miniConsole.addTextPair("Jours de rétention: ", srv.nbJourRetention)
                Case GetType(Chemin).Name
                    Dim chm = DirectCast(elem.Tag, Chemin)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Chemin")
                    miniConsole.addTextPair("Type logs: ", chm.typeLogs)
                    miniConsole.addTextPair("Chemin source: ", chm.getFullPathSource)
                    miniConsole.addTextPair("Chemin destination: ", chm.getFullPathDestination)
                Case GetType(FileInfo).Name
                    Dim fichier = DirectCast(elem.Tag, FileInfo)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Fichier de logs")
                    miniConsole.addTextPair("Nom: ", fichier.Name)
                    miniConsole.addTextPair("Date de création: ", fichier.CreationTime.toFrenchComplete)
                    miniConsole.addTextPair("Date de modification: ", fichier.LastWriteTime.toFrenchComplete)
                Case GetType(DirectoryInfo).Name
                    Dim dossier = DirectCast(elem.Tag, DirectoryInfo)
                    miniConsole.Foreground = Brushes.Black
                    miniConsole.addTextTitle("Dossier de logs")
                    miniConsole.addTextPair("Nom: ", dossier.Name)
                    miniConsole.addTextPair("Date de création: ", dossier.CreationTime.toFrenchComplete)
                    miniConsole.addTextPair("Date de modification: ", dossier.LastWriteTime.toFrenchComplete)
            End Select
        End If
    End Sub

    Private Sub testAllPaths_Unloaded(sender As Object, e As System.Windows.RoutedEventArgs) Handles Me.Unloaded
        stopScan()
    End Sub

    Sub stopScan()
        If stopBool = False Then
            loadingImg.LoadSmile(DirectCast(My.Resources.Resources.ic_warning, System.Drawing.Bitmap))
            stopBool = True
            r.consoleOut.addItim(New ConsoleTypes.warning(msg_cancelled, ""))
        End If
    End Sub

    Function getConstantSpace(str As String, max As Int32, desired As Integer) As String
        Dim outstr As String = ""
        Dim nb = max - str.Length + desired

        For i = 0 To nb
            outstr &= "   "
        Next

        Return outstr & vbTab
    End Function

    Function findNoeudFichierByTag(noeudParent As TreeViewItemWithIcons, fichier_x As FileInfo) As TreeViewItemWithIcons
        Dim noeudFichier = (From nf As TreeViewItemWithIcons In noeudParent.Items _
                           Select nf Where GetType(FileInfo).Name = nf.Tag.GetType.Name AndAlso DirectCast(nf.Tag, FileInfo) Is fichier_x).First

        Return noeudFichier
    End Function

    Sub updateTreeViewNodes(excepTest As Exception, noeudCheminSub As TreeViewItemWithIcons, noeudChemin As TreeViewItemWithIcons, noeudServeur As TreeViewItemWithIcons, noeudPlateforme As TreeViewItemWithIcons, path As String)
        If excepTest Is Nothing Then
            noeudCheminSub.Icon = My.Resources.micro_accept.ToImageSource
            noeudCheminSub.Tag = "Accès ok: " & path
        Else
            noeudCheminSub.Icon = My.Resources.micro_error.ToImageSource
            noeudChemin.Icon = My.Resources.micro_error.ToImageSource
            noeudServeur.Icon = My.Resources.micro_error.ToImageSource
            noeudPlateforme.Icon = My.Resources.ic_error.ToImageSource
            noeudCheminSub.Tag = excepTest.Message
        End If

        noeudChemin.IsExpanded = True
        noeudCheminSub.BringIntoView()
    End Sub
End Class
